<?php
class PlayList
{
  private $id;
  private $name;
  private $description;
  private $items;   //array
  private $share; //bool
  private $podcast; //bool
  private $tags;
  
  public function __construct($id='',$values=array(),$init = true)
  {
    if(empty($id) and !empty($values))//new playlist,insert
    {
      if(empty($values['name']))
      {
        //throw new Exception('missing parameter name');
      }
      $this->id           = uniqid('pls');
      $this->name         = htmlentities(utf8_decode($values['name']),ENT_QUOTES);
      $this->description  = '';
      $this->items        = $values['items'];
      $this->share        = 'F';
      $this->podcast      = 'F';// F For False !
      $this->tags         = '';
    }
    if(!empty($id) and empty($values))// display||delete
    {
      $this->id = $id;
      if($init)
      {
        $this->fromDB();
      }
    }
  }
  
  public function toDB()
  {
    $sql = "SELECT id from playlist WHERE id='".$this->id."'";
    $dbh = new dbSql();
    $res = $dbh->query($sql);
    if($res[0]['id'] == $this->id)
    {
      return($this->update());
    }
    else
    {
      return($this->insert());
    }
  }
  
  private function update()
  {
    $sql = "UPDATE playlist SET 
              name='".sqlite_escape_string($this->name)."', 
              description='".sqlite_escape_string($this->description)."',
              items='".sqlite_escape_string(serialize($this->items))."',
              share='".$this->share."',
              podcast='".sqlite_escape_string($this->podcast)."',
              tags='".sqlite_escape_string($this->tags)."' 
            WHERE id='".sqlite_escape_string($this->id)."' AND usr_id='".sqlite_escape_string($_SESSION['MczSession']->getLogin())."'";
    $dbh = new dbSql();
    $res = $dbh->exec($sql);
    if($res === 1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  private function insert()
  {
    $sql="INSERT INTO playlist 
    values( '".sqlite_escape_string($this->id)."',
            '".sqlite_escape_string($_SESSION['MczSession']->getLogin())."',
            '".sqlite_escape_string($this->name)."',
            '".sqlite_escape_string(serialize($this->items))."',
            '".sqlite_escape_string($this->description)."',
            '".sqlite_escape_string($this->share)."',
            '".sqlite_escape_string($this->podcast)."',
            '".sqlite_escape_string($this->tags)."')";
    $dbh = new dbSql();
    $res = $dbh->exec($sql);
    if($res === 1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  
  public function delete()
  {
    $sql = "DELETE FROM playlist WHERE id='".sqlite_escape_string($this->id)."' AND usr_id='".sqlite_escape_string($_SESSION['MczSession']->getLogin())."'";
    $dbh = new dbSql();
    $res = $dbh->exec($sql);
    return $res;
  }

  private function fromDB()
  {
    $sql = "SELECT * FROM playlist WHERE id='".$this->id."' AND usr_id='".$_SESSION['MczSession']->getLogin()."'";
    $dbh = new dbSql();
    $res = $dbh->query($sql);
    if(!empty($res))
    {
      //$this->id           = $res[0]['id'];
      $this->name         = $res[0]['name'];
      $this->description  = $res[0]['description'];
      $this->items        = unserialize($res[0]['items']);
      $this->share        = $res[0]['share'];//F -> False
      $this->podcast      = $res[0]['podcast'];// F -> False
      $this->tags         = $res[0]['tags'];
    }
  }
  
  public function stopPodcast()
  {
    $this->podcast = 'F';
  }
  
  public function startPodcast()
  {
    $this->podcast = 'V';
  }
  
  public static function isPodcast($podcastId,$songId)
  {
    $sql = "SELECT * FROM playlist WHERE id='".sqlite_escape_string($podcastId)."'";
    $dbh = new dbSql();
    $res = $dbh->query($sql);
    if(empty($res))
    {
      return false;
    }
    if($res[0]['podcast'] != 'V')
    {
      return false;
    }
    $items = unserialize($res[0]['items']);
    foreach($items as $item)
    {
      if($item['res_id'] == $songId)
      {
        return true;
      }
    }
    return false;
  }
  
  public static function rss($id)
  {
    $sql = "SELECT * FROM playlist WHERE id='".sqlite_escape_string($id)."'";
    $dbh = new dbSql();
    $res = $dbh->query($sql);
    if(empty($res))
    {
      return false;
    }
    if($res[0]['podcast'] == 'V')
    {
      if(empty($res[0]['description']))
      {
        $desc = 'Mychoonz generated podcast';
      }
      else
      {
        $desc = $res[0]['description'];
      }
      $rss_items = '';
      $pls_items = unserialize($res[0]['items']);
      foreach($pls_items as $item)
      {
        if($item['type'] == 'mczid')// Item must be a local file no to encourage bandwith leechers
        {
          $song = new Song($item['res_id']);
          $item_title = $song->getLabel();
          $item_description = $song->getTag('comment');
          $path_parts = pathinfo($_SERVER['SCRIPT_NAME']);
          if(ITUNES_FIX)// itune compatibility fix. Needs mod_rewrite.
          {
            $res_url = 'http://'.$_SERVER['HTTP_HOST'].$path_parts['dirname'].'/'.$id.'-'.$song->getId().'.mp3';
          }
          else
          {
            $res_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?c=dlpod&amp;podcast='.$id.'&amp;songId='.$song->getId();
          }

          $item_enclosure = $res_url;
          $item_length = $song->getFileSize();

          if(empty($item_description) or $item_description == 'Unknown')
          {
            $item_description = '';
          }
          else
          {
            $item_description = '<description><![CDATA['.$item_description.']]></description>';
          }
          $rss_items.= '<item>
                        <title>'.htmlspecialchars($item_title).'</title>
                        '.$item_description.'
                        <link>'.$res_url.'</link>
                        <enclosure url="'.$item_enclosure.'" length="'.$item_length.'" type="audio/mpeg"/>
                        </item>';
        }
      }
      $xml = XML_PROLOG
            .'<rss version="2.0">
              <channel>
              <title>'.htmlspecialchars(utf8_encode(html_entity_decode($res[0]['name'],ENT_QUOTES))).'</title>
              <description>'.$desc.'</description>
              <link>http://'.$_SERVER['HTTP_HOST'].'</link>
              '.$rss_items.'
              </channel>
              </rss>';
      return $xml;
    }
    else
    {
      return '';
    }
  }
  
  public function getItems()
  {
    return $this->items;
  }
  
  public function setTitle($title)
  {
    $this->name = htmlentities(utf8_decode($title),ENT_QUOTES);
  }
  
  public function getTitle()
  {
    return(utf8_encode(html_entity_decode($this->name)));
  }
  
  public function setItems($items)
  {
    $this->items = $items;
  }
  
  public function addItem($type,$label,$res_id)
  {
    if(empty($type) or empty($res_id))
    {
      return false;
    }
    $uid = uniqid('cue');
    $this->items[$uid] = array('id'=>$uid,'type'=>$type,'label'=>$label,'res_id'=>$res_id);
  }
  
  public function mkHtml()
  {
    if($_SESSION['MczSession']->can('dist'))
    {
      if($this->podcast == 'F')
      {
        $pod = '<input type="image"
        src="app/skin/transparent.gif"
        onmouseover="help(str.hlp_podcast_pls);"
        onclick="startPod(\''.$this->id.'\');"
        class="btnGoPod"/>&nbsp;';
      }
      elseif($this->podcast == 'V')
      {
        $pod = '<input type="image"
        src="app/skin/transparent.gif"
        onmouseover="help(str.hlp_nopodcast_pls);"
        onclick="stopPod(\''.$this->id.'\');"
        class="btnStopPod"/>&nbsp;';
      }
    }
    else
    {
      $pod = '';
    }
    $html = '<h2 onmouseover="help(str.hlp_click_to_edit);$(this).editable(\'?c=ajax\',{callback:function(){refreshPls();},saving:str.ui_saving,editClass:\'inlineEdit\',extraParams:{action:\'setPlsTitle\',plsId:\''.$this->id.'\',token:$(\'#token\').val()}});">'.utf8_encode(html_entity_decode($this->name)).'</h2>
      <input type="image"
        src="app/skin/transparent.gif"
        onmouseover="help(str.hlp_add_list_to_cue);"
        onclick="addPlsToCue(\''.$this->id.'\');"
        class="btnAddToCue"/>&nbsp;
      <input type="image"
        src="app/skin/transparent.gif"
        onmouseover="help(str.hlp_cue_to_pls);"
        onclick="cueToPls(\''.$this->id.'\');"
        class="btnSave"/>&nbsp;'.$pod;

    if(!empty($this->description))
    {
      $desc = '<div class="plsDesc">'.$this->description.'</div>';
    }
    else
    {
      $desc = '<!--<div class="plsDesc">'.STR_UI_NO_DESCRIPTION.'</div>-->';
    }
    if($this->podcast == 'V')
    {
      $podUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?c=pod&amp;pls='.$this->id;
      $html.= '<a href="'.$podUrl.'" target="_blank" onmouseover="help(str.hlp_go_to_podcast);"><img class="btnGoToPod" src="app/skin/transparent.gif" alt="podcast"/></a>';
    }
    
    $html.=$desc.'<ul class="plsItems">';
    $i=1;
    foreach($this->items as $item)
    {

      if($item['type'] == 'mczid')
      {
        $song = new Song($item['res_id']);
        $title = $song->getTag('title');
        $artist= $song->getTag('artist');
        $item['label'] = $artist.' - '.$title;
      }
      $html.='<li>'.str_pad($i,3,'0',STR_PAD_LEFT).'&nbsp;-&nbsp;<strong>'.$item['label'].'</strong></li>';
      $i++;
    }
    $html.='</ul>';
    
    return $html;
  }
  
  public static function getPlaylists($id = 'plsSelect',$labelLength = 40)
  {
    $sql = "SELECT ucwords(name) AS name,id FROM playlist WHERE usr_id='".$_SESSION['MczSession']->getLogin()."' ORDER BY low_case(name) ASC";
    $dbh = new dbSql();
    $dbh->registerFn('low_case','mb_strtolower');
    $dbh->registerFn('ucwords','ucwords');
    $res = $dbh->query($sql);
    $values['empty'] = STR_HLP_PLAYLISTS_LIST;
    foreach($res as $row)
    {
      $values[$row['id']] = $row['name'];
    }
    $html = Html::mkSelect(array('labelLength'=>$labelLength,'values'=>$values,'id'=>$id,'script'=>'onchange="displayPls(this.value);"'));
    $html.='&nbsp;<input type="image" src="app/skin/transparent.gif" class="btnPlsRemove" onclick="deletePlaylist($(\'#plsSelect\').val())"/>';
    return $html;
  }
  public static function getPlaylistsSelect($id = 'plsSelect2',$labelLength = 20)
  {
    $sql = "SELECT ucwords(name) AS name,id FROM playlist WHERE usr_id='".$_SESSION['MczSession']->getLogin()."' ORDER BY low_case(name) ASC";
    $dbh = new dbSql();
    $dbh->registerFn('low_case','mb_strtolower');
    $dbh->registerFn('ucwords','ucwords');
    $res = $dbh->query($sql);
    $values['new'] = STR_UI_NEW_PLS;
    foreach($res as $row)
    {
      $values[$row['id']] = $row['name'];
    }
    $html = Html::mkSelect(array('labelLength'=>$labelLength,'values'=>$values,'id'=>$id));
    return $html;
  }
}
?>
